/**
 * 树控制器
 */
(function (app, ng) {
    'use strict';

    /**
     * 注册控制器
     */
    app.controller('treeCtrl', Controller);

    /**
     * 依赖项
     */
    Controller.$inject = ['$scope', '$controller', 'module', 'treeService']
        .concat(['$stateParams', '$uibModal', 'dialogs']);

    /**
     * 声明控制器
     * @param $scope 当前作用域
     * @param $controller 控制器服务
     * @param module 当前模块
     * @param Service 当前服务
     * @param $stateParams 路由参数
     * @param $uibModal 模态框服务
     * @param dialogs 提示框服务
     * @constructor
     */
    function Controller($scope, $controller, module, Service, $stateParams, $uibModal, dialogs) {
        // 初始化
        var vm = this;
        extendResourceController();
        var iResource = vm.iResource;

        // 属性声明
        /*******************简单树 属性声明start*****************************************************************/
        //简单树对象
        vm.treeObj = {};
        //设置树的参数
        vm.treeSetting = {
            async: {
                url: ISS.getPath('/demo/asyncTree'),
                enable: true,
                dataType: "json",
                autoParam: ["id", "level"],
                otherParam: {"lang": ISS.lang},
                //  dataFilter: ajaxDataFilter//对 Ajax 返回数据进行预处理的函数
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            edit: {
                enable: true,
                removeTitle: getMessage("common.del"),
                renameTitle: getMessage("common.edit"),
                showRemoveBtn: function (treeId, treeNode) {//根节点不显示删除标记
                    return treeNode.level == 0 ? false : true;
                },
                showRenameBtn: function (treeId, treeNode) {//根节点不显示修改标记
                    return treeNode.level == 0 ? false : true;
                }
            },
            callback: {//回调函数
                onAsyncSuccess: function zTreeOnAsyncSuccess(event, treeId, treeNode) {
                    //默认展开第一个节点节点，触发根节点展开点击事件
                    if (angular.isUndefined(treeNode) || treeNode == null) {
                        $("#demoTree_1_switch").click();
                    } else {
                        $("#" + treeNode.tId + "_span").click();
                    }
                },
                onClick: function (event, treeId, treeNode, clickFlag) {//点击节点事件
                    $scope.$apply(function () {
                        vm.treeNode = treeNode;
                    });
                    // vm.treeObj.expandNode(treeNode, true, true, true);//展开全部节点
                },
                beforeEditName: zTreeBeforeEditName,//修改节点数据
                beforeRemove: zTreeBeforeRemove//删除节点数据
            }
        };
        /*******************简单树 属性声明end*****************************************************************/


        /*******************复选树 属性声明start*****************************************************************/
        //复选树
        vm.treeCheckboxObj = {};
        //设置树的参数
        vm.treeCheckboxSetting = {
            async: {
                url: ISS.getPath('/demo/asyncTree'),
                enable: true,
                dataType: "json",
                autoParam: ["id", "level"],
                otherParam: {"lang": ISS.lang}
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            check: {
                enable: true,
                autoCheckTrigger: true,
                chkboxType: {"Y": "p s", "N": "s"}
            },
            edit: {
                enable: true,
                removeTitle: getMessage("common.del"),
                renameTitle: getMessage("common.edit"),
                showRemoveBtn: false,
                showRenameBtn: false
            },
            callback: {//回调函数
                onAsyncSuccess: function zTreeOnAsyncSuccess(event, treeId, treeNode) {
                    //默认展开第一个节点节点，触发根节点展开点击事件
                    if (!treeNode) {
                        $("#demoCheckTree_1_switch").click();
                    } else {
                        vm.rootNode = treeNode;
                        $("#" + treeNode.tId + "_span").click();
                    }
                },
                onClick: function (event, treeId, treeNode, clickFlag) {//点击节点事件
                    $scope.$apply(function () {
                        vm.checkboxTreeNode = treeNode;
                    });
                    // vm.treeObj.expandNode(treeNode, true, true, true);//展开全部节点
                },
                onCheck: function zTreeOnCheck(event, treeId, treeNode) {
                    $scope.$apply(function () {
                        vm.treeCheckedNodes = vm.treeCheckboxObj.getCheckedNodes();
                    });

                }
            }
        };
        /*******************复选树 属性声明end*****************************************************************/


        /*******************单选树 属性声明start*****************************************************************/
        //单选树
        vm.treeRadioObj = {};
        //设置树的参数
        vm.treeRadioSetting = {
            async: {
                url: ISS.getPath('/demo/asyncTree'),
                enable: true,
                dataType: "json",
                autoParam: ["id", "level"],
                otherParam: {"lang": ISS.lang}
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
            },
            edit: {
                enable: true,
                removeTitle: getMessage("common.del"),
                renameTitle: getMessage("common.edit"),
                showRemoveBtn: false,
                showRenameBtn: false
            },
            callback: {//回调函数
                onAsyncSuccess: function zTreeOnAsyncSuccess(event, treeId, treeNode) {
                    //默认展开第一个节点节点，触发根节点展开点击事件
                    if (!treeNode) {
                        $("#demoRadioTree_1_switch").click();
                    } else {
                        vm.rootNode = treeNode;
                        $("#" + treeNode.tId + "_span").click();
                    }
                },
                onClick: function (event, treeId, treeNode, clickFlag) {//点击节点事件
                    $scope.$apply(function () {
                        vm.radioTreeNode = treeNode;
                    });
                    // vm.treeObj.expandNode(treeNode, true, true, true);//展开全部节点
                },
                onCheck: function zTreeOnCheck(event, treeId, treeNode) {
                    $scope.$apply(function () {
                        vm.radioTreeCheckedNodes = vm.treeRadioObj.getCheckedNodes();
                    });
                }
            }
        };
        /*******************单选树 属性声明end*****************************************************************/


        /*******************下拉树  属性声明start*****************************************************************/
        //下拉树
        vm.treeDownObj = {};
        //设置树的参数
        vm.treeDownSetting = {
            async: {
                url: ISS.getPath('/demo/asyncTree'),
                enable: true,
                dataType: "json",
                autoParam: ["id", "level"],
                otherParam: {"lang": ISS.lang}
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            check: {
                enable: true,
                autoCheckTrigger: true,
                chkboxType: {"Y": "p s", "N": "s"}
            },
            edit: {
                enable: true,
                removeTitle: getMessage("common.del"),
                renameTitle: getMessage("common.edit"),
                showRemoveBtn: false,
                showRenameBtn: false
            },
            callback: {//回调函数
                onAsyncSuccess: function zTreeOnAsyncSuccess(event, treeId, treeNode) {
                    //默认展开第一个节点节点，触发根节点展开点击事件
                    if (!treeNode) {
                        $("#demoDownTree_1_switch").click();
                    } else {
                        vm.rootNode = treeNode;
                        $("#" + treeNode.tId + "_span").click();
                    }
                },
                onClick: function (event, treeId, treeNode, clickFlag) {//点击节点事件
                    $scope.$apply(function () {
                        vm.downTreeNode = treeNode;
                    });
                    vm.treeObj.expandNode(treeNode, true, true, true);//展开全部节点
                },
                onCheck: function zTreeOnCheck(event, treeId, treeNode) {
                    $scope.$apply(function () {
                        vm.downTreeCheckedNodes = vm.treeDownObj.getCheckedNodes();
                        vm.selectDownNode = [];
                        angular.forEach(vm.downTreeCheckedNodes, function (node) {
                            vm.selectDownNode.push(node.name);
                        })
                    });
                }
            }

        };
        /*******************下拉树  属性声明end*****************************************************************/

        // 方法引用
        ng.extend(vm, {
            /*******************简单树 方法引用start*****************************************************************/
            ajaxDataFilter: ajaxDataFilter, // 对 Ajax 返回数据进行预处理的函数
            zTreeBeforeEditName: zTreeBeforeEditName, //修改节点数据
            zTreeBeforeRemove: zTreeBeforeRemove, //删除节点数据
            addOrUpdateNode: addOrUpdateNode // 修改或删除节点数据
            /*******************简单树 方法引用end*****************************************************************/
        });

        // 方法声明

        /**
         * 继承Restful控制器
         */
        function extendResourceController() {
            var controller = $controller('iResourceController', {$scope: $scope, module: module, iResource: Service});
            ng.extend(vm, controller);
        }

        /*******************简单树 方法声明 start*****************************************************************/
        /**
         * 对 Ajax 返回数据进行预处理的函数
         * @param treeId
         * @param parentNode
         * @param responseData
         * @returns {*}
         */
        function ajaxDataFilter(treeId, parentNode, responseData) {
            return responseData;
        }

        /**
         * 修改节点数据
         * @param treeId
         * @param treeNode
         * @returns {boolean}
         */
        function zTreeBeforeEditName(treeId, treeNode) {
            vm.addOrUpdateNode(treeNode);
            return false;
        }

        /**
         * 删除节点数据
         * @param treeId
         * @param treeNode
         * @returns {boolean}
         */
        function zTreeBeforeRemove(treeId, treeNode) {
            // 弹出确认删除提示信息
            var dlg = dialogs.confirm(undefined, getMessage("common.deleteConfirm"));
            dlg.result.then(function () {
                Service.deleteNode(treeNode.id).then(function (data) {
                    if (data.success === false) {
                        dialogs.notify(data);
                    } else {
                        dialogs.notify(undefined, getMessage("操作成功")).closed.then(function () {
                            vm.treeObj.reAsyncChildNodes(treeNode.getParentNode(), "refresh");
                        });
                    }
                });
            });
            return false;
        }

        /**
         * 删除和修改节点数据
         * @param treeNode
         */
        function addOrUpdateNode(treeNode) {

            if (angular.isUndefined(treeNode)) {//新增
                var selectNode = vm.treeObj.getSelectedNodes();
                if (selectNode.length < 1) {
                    dialogs.notify(undefined, getMessage("common.plzSelectOneRecourd"));
                    return;
                } else {
                    var parentTreeNode = selectNode[0];
                }
                if (parentTreeNode.type == 2) {
                    dialogs.notify(undefined, getMessage("叶子节点下不能新增节点"));
                    return;
                }
                var param = {isEdit: false, parentTreeNode: parentTreeNode};
            } else {
                var param = {treeNode: treeNode, isEdit: true};//修改
            }

            var modalInstance = $uibModal.open({
                animation: true,
                backdrop: true,
                size: 'md',
                templateUrl: 'demo/components/tree/add-node.html',
                controller: 'addOrUpdateTreeNodeCtrl',
                controllerAs: 'vm',
                resolve: {
                    module: module,
                    param: function () {
                        return param;
                    }
                }
            });
            modalInstance.result.then(function (result) {//这是一个接收模态框返回值的函数
                if (!param.isEdit) {//新增
                    vm.treeObj.reAsyncChildNodes(parentTreeNode, "refresh");
                } else {//修改
                    vm.treeObj.updateNode(result);
                }
            });
        };
        /*******************简单树 方法声明 end*****************************************************************/

    }
})(iApp.module(), window.angular);